package com.pengxun.manager.service.system.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.pengxun.manager.dao.system.UserRoleDao;
import com.pengxun.manager.model.system.UserRole;
import com.pengxun.manager.model.system.Userinfo;
import com.pengxun.manager.service.system.LoginService;
import com.pengxun.manager.service.system.UserRoleService;
import com.pengxun.manager.vo.AssignRolesVO;
import com.szeastroc.common.jdbc.page.Page;


@Service
public class UserRoleServiceImpl implements UserRoleService{

	@Resource
	private UserRoleDao userRoleDao;

	@Resource
    private LoginService loginService;
	
	@Override
	public int insert(UserRole userRole) {
		return userRoleDao.insert(userRole);
	}
	
    @Override
    public int update(UserRole userRole){
        return userRoleDao.update(userRole);
    }
   	
    @Override
    public int delete(Integer id){
       return userRoleDao.delete(id);
 	}
   
   @Override
    public Page findByPage(Page page){
    	 List<UserRole> userRoles = userRoleDao.findByPage(page);
    	 page.setData(userRoles);
         return page;
    }

   @Override
   public List<UserRole> findByUserId(Long userId){
	   return userRoleDao.findByUserId(userId);
   }
   
   @Override
   public int deleteByroleCode(String roleCode){
	   return userRoleDao.deleteByroleCode(roleCode);
   }


   @Override
   public void assignRoles(AssignRolesVO assignRolesVO){

	    List<UserRole> list = new ArrayList<>();
	    Date date = new Date();

       Userinfo currentUser = loginService.getCurrentUser();

       for (String roleCode:assignRolesVO.getRoleCodes()){
	        UserRole userRole = new UserRole();
	        userRole.setUserId(assignRolesVO.getUserId());
	        userRole.setRoleCode(roleCode);
	        userRole.setCreateDate(date);
	        userRole.setCreateBy(currentUser.getUserId());

	        list.add(userRole);
        }
       userRoleDao.deleteByUserId(assignRolesVO.getUserId());
       userRoleDao.batchInsert(list);
   }
}
